package httpHandler

import (
	"context"
	"fmt"
	"gitee.com/zaiqiang231/lovesport-authz-service/app/authorizer"
	"gitee.com/zaiqiang231/lovesport-authz-service/app/constant"
	"gitee.com/zaiqiang231/lovesport-authz-service/app/rpc"
	"gitee.com/zaiqiang231/lovesport-user-service/app/rpc/proto"
	"github.com/gin-gonic/gin"
	"github.com/ory/ladon"
	"net/http"
)

func AuthFunc(c *gin.Context) {
	header := c.Request.Header.Get("Authorization")
	if len(header) == 0 {
		WriteResponse(c, http.StatusBadRequest, "Authorization header cannot be empty.", nil)
		c.Abort()
		return
	}
	var rawJWT string
	// Parse the header to get the token part.
	fmt.Sscanf(header, "Bearer %s", &rawJWT)

	response, err := rpc.GetUserRpc().UserRpcServiceClient.TokenCheck(context.Background(), &proto.TokenCheckRequest{Token: rawJWT})
	if err != nil {
		WriteResponse(c, http.StatusBadRequest, err.Error(), nil)
		c.Abort()
		return
	}

	if len(response.Message) > 0 {
		WriteResponse(c, http.StatusBadRequest, response.Message, nil)
		c.Abort()
		return
	}

	c.Set(constant.AuthIdentityKey, response.Identity)
	c.Next()
}

func Authorize(c *gin.Context) {
	var r ladon.Request
	if err := c.ShouldBind(&r); err != nil {
		WriteResponse(c, http.StatusBadRequest, err.Error(), nil)
		return
	}

	if r.Context == nil {
		r.Context = ladon.Context{}
	}
	r.Context[constant.AuthIdentityKey] = c.GetString(constant.AuthIdentityKey)
	auth := authorizer.NewAuthorizer(&authorizer.AuthorizationClient{})
	rsp := auth.Authorize(&r)

	WriteResponse(c, 0, "success", rsp)
}
